<?php
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: login.php");
    exit;
}
require_once 'db.php';
$stmt = $pdo->query('SELECT content FROM knowledge_base ORDER BY id DESC LIMIT 1');
$row = $stmt->fetch();
$saved_content = $row ? $row['content'] : '';
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>知识库-谭宝龙</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prism-themes/themes/prism-vsc-dark-plus.css">
    <link rel="icon" type="image/x-icon" href="logo.ico">
    <style>
        /* 移除测试样式 */
        /* body { background: #ffcccc !important; } */
        body {
            background: #f4f6fa;
            font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
            color: #222;
            font-size: 16px;
            line-height: 1.7;
        }
        .navbar {
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
            background: linear-gradient(90deg, #1976d2 0%, #1565c0 100%);
        }
        .navbar .navbar-brand {
            font-size: 1.5rem;
            font-weight: bold;
            letter-spacing: 1px;
            color: #fff !important;
        }
        .navbar .nav-link, .navbar .nav-item {
            color: #e3eaf2 !important;
            font-size: 1rem;
            margin-left: 10px;
        }
        .navbar .nav-link:hover {
            color: #fff !important;
            text-decoration: underline;
        }
        .content-container {
            margin-top: 40px;
            margin-bottom: 40px;
        }
        .main-content {
            margin-left: auto !important;
            max-width: 1600px !important;
            width: 100% !important;
            padding: 0 24px !important;
            margin-right: auto !important;
            margin-top: 40px !important;
            margin-bottom: 40px !important;
            box-sizing: border-box !important;
        }
        .card {
            border-radius: 18px;
            box-shadow: 0 4px 24px rgba(0,0,0,0.10);
            border: none;
            background: #fff;
        }
        .card-header {
            background: transparent;
            border-bottom: none;
            padding-bottom: 0.5rem;
        }
        .card-title {
            font-size: 1.3rem;
            font-weight: bold;
            color: #1976d2;
            letter-spacing: 1px;
        }
        #viewContent {
            padding: 32px 32px 24px 32px;
            background: #fff;
            border-radius: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
            min-height: 300px;
        }
        #contentForm {
            padding: 32px 32px 24px 32px;
            background: #fff;
            border-radius: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
        }
        .toc-container {
            position: fixed !important;
            left: 30px !important;
            top: 110px !important;
            width: 260px !important;
            max-width: 90vw !important;
            min-width: 160px !important;
            max-height: calc(100vh - 140px) !important;
            overflow-y: auto !important;
            background: #f8fafc !important;
            padding: 22px 14px 16px 14px !important;
            border-radius: 16px !important;
            box-shadow: 0 4px 24px rgba(0,0,0,0.10) !important;
            font-size: 15px !important;
            font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif !important;
            border: 1px solid #e5e7eb !important;
            z-index: 1000 !important;
        }
        .toc-container h5 {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 14px;
            color: #1976d2;
            letter-spacing: 1px;
        }
        .toc-container ul {
            list-style: none;
            padding-left: 0;
            margin: 0;
        }
        .toc-container li {
            margin: 4px 0;
            padding-left: 0.8em;
            border-left: 2px solid #e0e7ef;
            transition: background 0.2s;
        }
        .toc-container li li {
            padding-left: 1.5em;
            border-left: 2px solid #f0f3fa;
        }
        .toc-container a {
            color: #333;
            text-decoration: none;
            display: block;
            border-radius: 6px;
            padding: 2px 6px;
            transition: background 0.2s, color 0.2s;
        }
        .toc-container a:hover {
            background: #e0e7ef;
            color: #1976d2;
        }
        #floatingEditBtn {
            position: fixed;
            top: 32px;
            right: 40px;
            z-index: 999;
            box-shadow: 0 2px 8px rgba(0,0,0,0.10);
            border-radius: 8px;
            padding: 10px 28px;
            font-size: 17px;
            font-weight: bold;
            background: linear-gradient(90deg, #1976d2 0%, #1565c0 100%);
            border: none;
            color: #fff;
            letter-spacing: 1px;
            transition: background 0.2s, box-shadow 0.2s;
        }
        #floatingEditBtn:hover {
            background: linear-gradient(90deg, #1565c0 0%, #1976d2 100%);
            box-shadow: 0 4px 16px rgba(25, 118, 210, 0.15);
            color: #fff;
        }
        @media (max-width: 1400px) {
            .main-content {
                margin-left: 280px !important;
                max-width: 1200px !important;
            }
            .toc-container {
                width: 220px !important;
            }
        }
        @media (max-width: 1200px) {
            .main-content {
                margin-left: auto !important;
                max-width: 95vw !important;
            }
            .toc-container {
                display: none !important;
            }
        }
        @media (max-width: 992px) {
            .main-content {
                margin-left: 0 !important;
                max-width: 100vw !important;
                padding: 0 8px !important;
            }
            .toc-container {
                display: none !important;
            }
        }
        @media (max-width: 768px) {
            .container {
                padding: 0 4px !important;
            }
            #viewContent, #contentForm {
                padding: 10px !important;
            }
            .card {
                border-radius: 10px !important;
            }
            .main-content {
                margin-top: 12px !important;
                margin-bottom: 12px !important;
            }
        }
        @media (max-width: 576px) {
            .navbar .navbar-brand {
                font-size: 1.1rem !important;
            }
            .navbar .nav-link {
                font-size: 0.85rem !important;
            }
            #floatingEditBtn {
                top: 8px !important;
                right: 8px !important;
                font-size: 13px !important;
                padding: 5px 10px !important;
            }
            .content-container {
                margin-top: 8px;
                margin-bottom: 8px;
            }
            #viewContent, #contentForm {
                padding: 6px 2px;
            }
        }
        /* 标题美化 */
        #viewContent h1, #editor h1 { font-size: 28px; font-weight: bold; margin: 1.2em 0 0.7em 0; line-height: 1.2; }
        #viewContent h2, #editor h2 { font-size: 22px; font-weight: bold; margin: 1.1em 0 0.6em 0; line-height: 1.25; }
        #viewContent h3, #editor h3 { font-size: 18px; font-weight: bold; margin: 1em 0 0.5em 0; line-height: 1.3; }
        #viewContent h4, #editor h4 { font-size: 16px; font-weight: bold; margin: 0.9em 0 0.4em 0; line-height: 1.35; }
        .edit-mode {
            display: none;
        }
        .view-mode {
            display: block;
        }
        .copy-btn {
            position: absolute;
            top: 8px;
            right: 12px;
            background: #007bff;
            color: #fff;
            border: none;
            border-radius: 3px;
            padding: 2px 10px;
            font-size: 12px;
            cursor: pointer;
            opacity: 0.8;
            z-index: 10;
            transition: opacity 0.2s;
        }
        .copy-btn:hover {
            opacity: 1;
        }
        /* 去除所有Prism高亮token的背景色和box-shadow */
        .token,
        .token.comment,
        .token.prolog,
        .token.doctype,
        .token.cdata,
        .token.punctuation,
        .token.namespace,
        .token.deleted,
        .token.symbol,
        .token.property,
        .token.tag,
        .token.constant,
        .token.boolean,
        .token.number,
        .token.selector,
        .token.attr-name,
        .token.string,
        .token.char,
        .token.builtin,
        .token.inserted,
        .token.operator,
        .token.entity,
        .token.url,
        .token.atrule,
        .token.attr-value,
        .token.keyword,
        .token.function,
        .token.class-name,
        .token.regex,
        .token.important,
        .token.variable,
        .token.bold,
        .token.italic,
        .token.parameter,
        .token.interpolation,
        .token.interpolation-punctuation,
        .token.script,
        .token.script-punctuation,
        .token.plain-text,
        .token.property-access,
        .token.error,
        .token.warning {
            background: none !important;
            box-shadow: none !important;
        }
        html { scroll-behavior: smooth; }
        #viewContent img,
        #editor img {
            max-width: 100%;
            height: auto;
            display: block;
            margin: 12px auto;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
        }
        .navbar .navbar-nav {
            gap: 18px;
        }
        .navbar .nav-link, .navbar .nav-item {
            margin-left: 18px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="https://job.lahong.top:8888/">知识库系统</a>
            <div class="navbar-nav ms-auto">
                <span class="nav-item nav-link text-light">欢迎, <?php echo htmlspecialchars($_SESSION['username']); ?></span>
                <a class="nav-link" href="logout.php">退出</a>
            </div>
        </div>
    </nav>

    <!-- 目录 -->
    <div class="toc-container">
        <h5>目录</h5>
        <div id="toc"></div>
    </div>

    <div class="container content-container main-content">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">知识库内容</h5>
                    </div>
                    <div class="card-body">
                        <!-- 浏览模式 -->
                        <div id="viewContent" class="view-mode">
                            <?php echo $saved_content; ?>
                        </div>
                        <!-- 编辑模式 -->
                        <form id="contentForm" method="POST" action="save_content.php" class="edit-mode" style="display:none;">
                            <textarea id="editor" name="content"><?php echo htmlspecialchars($saved_content); ?></textarea>
                            <div class="mt-3">
                                <button type="submit" class="btn btn-success">保存</button>
                                <button type="button" class="btn btn-secondary" id="cancelEdit">取消</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <button id="floatingEditBtn" class="btn btn-primary">编辑模式</button>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tinymce@6.8.3/tinymce.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tinymce-lang/langs/zh_CN.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-css.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-java.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-sql.min.js"></script>
    <script>
        $(document).ready(function() {
            let isEditMode = false;
            // 初始化编辑器（只初始化一次）
            tinymce.init({
                selector: '#editor',
                language: 'zh_CN',
                height: 500,
                apiKey: '0irfv0uo3fjmz4r0t5z3nux8fh3fo6uo151xpp8bwu8antyi', // 请替换为您的TinyMCE API密钥
                plugins: [
                    'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
                    'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                    'insertdatetime', 'media', 'table', 'help', 'wordcount', 'codesample'
                ],
                toolbar: 'undo redo | blocks | ' +
                    'bold italic backcolor | alignleft aligncenter ' +
                    'alignright alignjustify | bullist numlist outdent indent | ' +
                    'removeformat | codesample code | help',
                block_formats: '段落=p; 标题 1=h1; 标题 2=h2; 标题 3=h3; 标题 4=h4; 标题 5=h5; 标题 6=h6',
                codesample_languages: [
                    { text: 'HTML/XML', value: 'markup' },
                    { text: 'JavaScript', value: 'javascript' },
                    { text: 'CSS', value: 'css' },
                    { text: 'PHP', value: 'php' },
                    { text: 'Python', value: 'python' },
                    { text: 'Java', value: 'java' },
                    { text: 'SQL', value: 'sql' }
                ],
                setup: function(editor) {
                    editor.on('change', function() {
                        updateTOC();
                        addCopyButtons();
                    });
                },
                init_instance_callback: function(editor) {
                    updateTOC();
                    Prism.highlightAll();
                    addCopyButtons();
                }
            });

            // 切换模式
            $('#floatingEditBtn').click(function() {
                isEditMode = !isEditMode;
                if (isEditMode) {
                    $('#viewContent').hide();
                    $('#contentForm').show();
                    // AJAX 获取数据库最新内容
                    function setEditorContentWhenReadyWithAjax() {
                        var editor = tinymce.get('editor');
                        if (editor && editor.initialized) {
                            $.get('get_content.php', function(data) {
                                editor.setContent(data);
                            });
                        } else {
                            setTimeout(setEditorContentWhenReadyWithAjax, 100);
                        }
                    }
                    setEditorContentWhenReadyWithAjax();
                    $(this).text('浏览模式');
                } else {
                    const content = tinymce.get('editor').getContent();
                    $('#viewContent').html(content).show();
                    $('#contentForm').hide();
                    $(this).text('编辑模式');
                    Prism.highlightAll();
                    updateTOC();
                    addCopyButtons();
                }
            });
            // 取消编辑
            $('#cancelEdit').click(function() {
                isEditMode = false;
                $('#viewContent').show();
                $('#contentForm').hide();
                $('#floatingEditBtn').text('编辑模式');
                tinymce.get('editor').setContent($('#viewContent').html());
                updateTOC();
                addCopyButtons();
            });

            // 目录生成
            function updateTOC() {
                let content = '';
                if (isEditMode && tinymce.get('editor')) {
                    content = tinymce.get('editor').getContent();
                } else {
                    content = $('#viewContent').html();
                }
                const $content = $('<div>').html(content);
                const $toc = $('#toc');
                $toc.empty();
                const headings = $content.find('h1, h2, h3, h4, h5, h6');
                let tocHtml = '<ul>';
                let numberStack = [];
                let lastLevel = 1;
                headings.each(function(index) {
                    const $heading = $(this);
                    const level = parseInt($heading.prop('tagName').substring(1));
                    const text = $heading.text();
                    const id = 'heading-' + index;
                    $heading.attr('id', id);
                    // 同步id到页面实际DOM
                    const realHeading = $('#viewContent').find($heading.prop('tagName')).eq($content.find($heading.prop('tagName')).index($heading));
                    if (realHeading.length) realHeading.attr('id', id);
                    if (numberStack.length < level) {
                        while (numberStack.length < level) numberStack.push(0);
                    } else if (numberStack.length > level) {
                        numberStack = numberStack.slice(0, level);
                    }
                    numberStack[level - 1]++;
                    for (let i = level; i < numberStack.length; i++) numberStack[i] = 0;
                    const numberStr = numberStack.slice(0, level).join('.') + ' ';
                    if (level > lastLevel) {
                        tocHtml += '<ul>'.repeat(level - lastLevel);
                    } else if (level < lastLevel) {
                        tocHtml += '</ul>'.repeat(lastLevel - level);
                    }
                    tocHtml += `<li><a href="#${id}">${numberStr}${text}</a></li>`;
                    lastLevel = level;
                });
                tocHtml += '</ul>'.repeat(lastLevel - 1);
                $toc.html(tocHtml);
                // 目录点击平滑滚动
                $toc.find('a').off('click').on('click', function(e) {
                    e.preventDefault();
                    const targetId = $(this).attr('href').replace('#', '');
                    const $target = $('#' + targetId);
                    if ($target.length) {
                        $('html, body').animate({ scrollTop: $target.offset().top - 30 }, 400);
                    }
                });
            }
            // 复制按钮功能
            function addCopyButtons() {
                $(".copy-btn").remove();
                $("pre > code").each(function() {
                    var pre = $(this).parent();
                    if (pre.find('.copy-btn').length === 0) {
                        var btn = $('<button class=\"copy-btn\">复制</button>');
                        pre.css('position', 'relative');
                        btn.appendTo(pre);
                        btn.click(function(e) {
                            e.preventDefault();
                            var code = $(this).siblings('code').text();
                            copyTextToClipboard(code);
                            $(this).text('已复制!');
                            var that = this;
                            setTimeout(function() { $(that).text('复制'); }, 1200);
                        });
                    }
                });
            }
            function copyTextToClipboard(text) {
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(text);
                } else {
                    var textarea = document.createElement('textarea');
                    textarea.value = text;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                }
            }
            // 初始渲染
            updateTOC();
            Prism.highlightAll();
            addCopyButtons();
        });
    </script>
</body>
</html> 